/** 关于文件的一些方法 */
import { uploadDocs, getPicture, deleteImg, uploadWatermarkDocs } from "@/api/doc.js";
import CONFIG from "@/config/path.js";
import { uploadFile } from '@/utils/request'
import { getToken } from '@/utils/auth.js'
export default {
	methods: {
		/**
		 * 上传文件
		 * @param {Array} fileArray 上传的文件列表
		 * @param {number} docId 对应的docId
		 */
		uploadFileList(fileArray, docId = 0, params, config = {}) {
			return new Promise(async (resolve, reject) => {
				if(fileArray.length) {
					try {
						if(!docId) {
							docId = JSON.parse(await uploadDocs({ formData: {...params}, fileList: [fileArray[0]],filePath: fileArray[0].url || "", ...config })).result.id;
							fileArray = fileArray.slice(1, fileArray.length);
						}
						for(const item of fileArray) {
							await uploadFile({ url: "rest/doc/uploadDoc", formData: {docId, ...params},files:[{name:'attach', uri: item.url, code: item.code}], filePath:item.url, ...config });
						}
					} catch (err) {
						reject(err)
					}
				}
				resolve(docId);
			});
		},
		/**
		 * dataList []  水印数据
		**/
		uploadWaterMark(fileArray, dataList, docId = 0, params, config = {}, name) {
			return new Promise(async (resolve, reject) => {
				if(fileArray.length) {
					try {
						if(!docId) {
							docId = JSON.parse(await uploadWatermarkDocs({ 
								formData: {...params, projectId:uni.getStorageSync("isOwner"), dataList:JSON.stringify(dataList)}, 
								fileList: [fileArray[0]],
								filePath: fileArray[0].url || "", 
								...config,
								name
							}
							)).result.id;
							fileArray = fileArray.slice(1, fileArray.length);
						}
						for(const item of fileArray) {
							await uploadFile({ 
								url: "composite/picture/addPictureText", 
								formData: {docId, ...params, projectId:uni.getStorageSync("isOwner"), dataList:JSON.stringify(dataList)},
								files:[{name:'file', uri: item.url}], 
								filePath:item.url, 
								...config,
								 name
								});
						}
					} catch (err) {
						reject(err)
					}
				}
				resolve(docId);
			});
		},
		
		
		/**
		 * 通过文件的docId获取文件列表
		 * @param {number} docId 文件的docId
		 * @return {Array<any>}
		 */
		getFileListByDocId(docId) {
			return new Promise(resolve => {
				if(!docId) {
					resolve([]);
				}
				else {
					getPicture({docId}).then(res => {
						if (res.success) {
							(res.result || []).forEach(item => {
								item.url = CONFIG.IMG_FILE_URL + item.fileName;
							});
							resolve(res.result);
						}
					});
				}
			});
		},
		
		/**
		 * 删除文件
		 * @param {number} id 文件id
		 * */
		removeFileById(id) {
			if(!id) {
				return;
			}
			return new Promise(resolve => {
				deleteImg({id}).then(() => {
					resolve();
				});
			});
		},
	}
}